package com.neu.fenli2023623.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.neu.fenli2023623.util.JwtUtils;
import com.neu.fenli2023623.util.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class LoginAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    @Autowired
    private JwtUtils jwtUtils;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //存放authentication到SecurityContextHolder，后续security就能获取到当前登录的用户信息了
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //得到认证后存放的用户信息，此类的定义在后面，可以理解该类之后再完善此处内容，把框架先搭建起来
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        String token = jwtUtils.generateToken(loginUser.getUsername());
        //以json的形式给前台影响数据，包括菜单信息
        response.setContentType("application/json;charset=UTF-8");
        String string = new ObjectMapper().writeValueAsString(ResultVo.ok().data("rightList",loginUser.getRightVos()).data("token",token));
        response.getWriter().println(string);
    }
}